
package com.tenentia.pcmps.swm.web.jsf.util;

import javax.el.MethodExpression;
import javax.faces.FactoryFinder;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.context.FacesContextFactory;
import javax.faces.event.ActionEvent;
import javax.faces.event.MethodExpressionActionListener;
import javax.faces.lifecycle.Lifecycle;
import javax.faces.lifecycle.LifecycleFactory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 * @author tEnEntia, S.L.N.E.
 * 
 */
public class JSFUtilities {

	private JSFUtilities() {

		super();
	}

	public static MethodExpressionActionListener createActionListenerMethodExpression(String methodExpressionString) {

		return new MethodExpressionActionListener(createMethodExpression(methodExpressionString, null, new Class[] { ActionEvent.class }));
	}

	public static MethodExpression createActionMethodExpression(String methodExpressionString) {

		return createMethodExpression(methodExpressionString, String.class, null);
	}

	public static MethodExpression createMethodExpression(String methodExpressionString, Class<?> expectedReturnType, Class<?>[] expectedParameters) {

		FacesContext facesContext = FacesContext.getCurrentInstance();
		MethodExpression methodExpression = facesContext.getApplication().getExpressionFactory().createMethodExpression(facesContext.getELContext(), methodExpressionString, expectedReturnType, expectedParameters);
		return methodExpression;
	}

	public static Object getManagedObject(String objectName) {

		FacesContext facesContext = FacesContext.getCurrentInstance();

		Object requestedObject = null;

		try {
			requestedObject = facesContext.getApplication().getELResolver().getValue(facesContext.getELContext(), null, objectName);
		} catch (Exception e) {
			requestedObject = null;
		}

		return requestedObject;
	}

	public static FacesContext getFacesContext(HttpServletRequest request, HttpServletResponse response, String s) {

		FacesContext facesContext = FacesContext.getCurrentInstance();

		if (null == facesContext) {
			FacesContextFactory contextFactory = (FacesContextFactory) FactoryFinder.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
			LifecycleFactory lifecycleFactory = (LifecycleFactory) FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
			Lifecycle lifecycle = lifecycleFactory.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE);

			facesContext = contextFactory.getFacesContext(request.getSession().getServletContext(), request, response, lifecycle);

			UIViewRoot view = facesContext.getApplication().getViewHandler().createView(facesContext, s);

			facesContext.setViewRoot(view);
		}

		return facesContext;
	}
}
